import { Component, ElementRef, Input } from "@angular/core";
import { Content } from "ionic-angular";

@Component({
    selector: 'adp-lazyload',
    templateUrl: 'adp-lazyload.html'
})
export class AdpLazyloadComponent {

    //图片真实地址
    @Input() lazysrc: string;
    //图片的className
    @Input() className: string;
    //页面的content组件
    @Input() content: Content;
    //图片距离屏幕多远时开始加载，单位 'px'
    @Input() distance: number;
    //第一个offsetTop 不为0的父级dom元素（详情问 Bert）
    @Input() wrapper;

    private relSrc: string = '';
    private seeHeight = document.documentElement.clientHeight;
    private relImg;

    constructor(private elRef: ElementRef) {
    }

    getSrc() {
        return this.lazysrc;
    }

    doLoadImg() {
        if (this.relSrc !== this.lazysrc) {
            this.relImg.src = this.relSrc = this.lazysrc;
        }
    }

    needLoading() {
        return this.wrapper.offsetTop < this.seeHeight + this.content.scrollTop - this.distance;
    }

    cacheImg(getImg: Promise<any>) {
        this.relImg = this.elRef.nativeElement.querySelector(`.${this.className}`);
        if (!this.relSrc) {
            getImg.then((res) => {
                try {
                    this.relImg.src = this.relSrc = res;
                } catch (e) {
                }
            });
        }
    }

    /**
     * 计算是否该加载
     */
    compute() {
        this.relImg = this.elRef.nativeElement.querySelector(`.${this.className}`);
        if (this.relSrc === this.lazysrc) {
            return;
        }
        if (this.needLoading()) {
            this.doLoadImg();
        }
    }
}
